//
//  SearchHotView.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//

#import "SearchHotView.h"
#import "SearchCollectionViewCell.h"
@interface SearchHotView()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)UICollectionView* collectionView;
@property (nonatomic, strong)ObjectAFNetWorking* objectAFNet;
@property (nonatomic, strong)NSDictionary*   dic;
@property (nonatomic, strong)NSMutableArray* datasource;
@property (nonatomic, strong)NSMutableArray* widthArr;
@property (nonatomic, assign)CGFloat         sheight;
@property (nonatomic, strong)UILabel*         label;
@end

@implementation SearchHotView

-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if(self)
    {
        [self initView];
    }
    return self;
}
-(void)initView
{
    self.objectAFNet=[[ObjectAFNetWorking alloc]init];
    self.datasource=[NSMutableArray new];
    self.widthArr=[NSMutableArray new];

    self.label=[[UILabel alloc]initWithFrame:CGRectMake(wid(20),0,SCREEN_WIDTH-wid(40),wid(80))];
    self.label.text=@"热门搜索";
    self.label.textColor=[UIColor blackColor];
    self.label.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(12)];
    [self addSubview:self.label];
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection =  UICollectionViewScrollDirectionVertical;
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0,wid(80),SCREEN_WIDTH,wid(20)) collectionViewLayout:flowLayout];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator=NO;
    _collectionView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    [_collectionView registerNib:[UINib nibWithNibName:@"SearchCollectionViewCell" bundle: nil] forCellWithReuseIdentifier:@"ITEM"];
    _collectionView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    self.sheight=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont systemFontOfSize:FontSize(10)] andWidth:wid(100)]+wid(20);
    [self addSubview:_collectionView];
    [self getData];
}
-(void)getData
{
//    [self.datasource removeAllObjects];
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/search_Json.json"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSData* dataString=[NSData dataWithContentsOfFile:filePath];
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        [self.datasource removeAllObjects];
        [self.widthArr removeAllObjects];
        [self.datasource addObjectsFromArray:dic[@"data"]];
        for(int i=0;i<self.datasource.count;i++)
        {
            CGFloat widht=[GC_OCTool getWidthForLabel:self.datasource[i] andFont:[UIFont systemFontOfSize:FontSize(10)] andHeight:wid(100)]+wid(25)*2;
            [self.widthArr addObject:[NSString stringWithFormat:@"%lf",widht]];
        }
        [self.collectionView reloadData];
        [self.collectionView layoutIfNeeded];
        self.frame=CGRectMake(0,self.frame.origin.y,SCREEN_WIDTH,self.collectionView.contentSize.height+wid(80)+wid(80));
        self.collectionView.frame=CGRectMake(self.frame.origin.x,wid(80),self.frame.size.width,self.collectionView.contentSize.height);
        [self.collectionView reloadData];
        [GC_OCTool saveFileAction:filePath];
    }else
    {
        [self.objectAFNet getUrlStr:[NSString stringWithFormat:@"%@/api/index/HotSearch",server_addr] finish:^(id  _Nonnull dataString) {
            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/search_Json.json"];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:nil];
            }
            [dataString writeToFile:filePath atomically:YES];
            [self.datasource removeAllObjects];
            [self.widthArr removeAllObjects];
            [self.datasource addObjectsFromArray:dic[@"data"]];
            for(int i=0;i<self.datasource.count;i++)
            {
                CGFloat widht=[GC_OCTool getWidthForLabel:self.datasource[i] andFont:[UIFont systemFontOfSize:FontSize(10)] andHeight:wid(100)]+wid(25)*2;
                [self.widthArr addObject:[NSString stringWithFormat:@"%lf",widht]];
            }
            [self.collectionView reloadData];
            [self.collectionView layoutIfNeeded];
            self.frame=CGRectMake(0,self.frame.origin.y,SCREEN_WIDTH,self.collectionView.contentSize.height+wid(80)+wid(80));
            self.collectionView.frame=CGRectMake(self.frame.origin.x,wid(80),self.frame.size.width,self.collectionView.contentSize.height);
            [self.collectionView reloadData];
        } andError:^(NSError * _Nonnull error) {
        }];
    }

    
}
#pragma -collectionview make
//整体
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0,wid(10),0,wid(10));//分别为上、左、下、右
}
//大小
-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath
{
    CGFloat width=[self.widthArr[indexPath.row] floatValue];
    return CGSizeMake(width,self.sheight);
}
//列
-(CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return wid(10);
}
//行
-(CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return wid(10);
}
#pragma mark - tableview delegate and datasource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _datasource.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCollectionViewCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"ITEM" forIndexPath:indexPath];
    CGFloat width=[self.widthArr[indexPath.row] floatValue];
    cell.backImageView.frame=CGRectMake(0,0,width,self.sheight);
    cell.naemLabel.frame=CGRectMake(0,0,width,self.sheight);
    cell.naemLabel.text=self.datasource[indexPath.row];
    cell.naemLabel.textColor=RBG(100,100,100);
    cell.backImageView.layer.masksToBounds=YES;
    cell.backImageView.layer.cornerRadius=self.sheight/2.0;
    cell.naemLabel.textAlignment=NSTextAlignmentCenter;
    cell.naemLabel.font=[UIFont systemFontOfSize:FontSize(10)];
    cell.backImageView.backgroundColor=RBG(240,240,240);
    return cell;
}
//进行点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray* array=[[NSUserDefaults standardUserDefaults]objectForKey:@"searchArr"];
    NSMutableArray* newArr=[NSMutableArray new];
    NSString* str=self.datasource[indexPath.row];
    if([array containsObject:str])
    {
        [newArr addObjectsFromArray:array];
        for(int i=0;i<newArr.count;i++)
        {
            if([newArr[i] isEqualToString:str])
            {
                [newArr removeObjectAtIndex:i];
            }
        }
        [newArr insertObject:str atIndex:0];
    }else
    {
        [newArr addObjectsFromArray:array];
        for(int i=0;i<newArr.count;i++)
        {
            if([newArr[i] isEqualToString:str])
            {
                [newArr removeObjectAtIndex:i];
            }
        }
        [newArr insertObject:str atIndex:0];
    }
    //保存好
    [[NSUserDefaults standardUserDefaults]setObject:newArr forKey:@"searchArr"];
    [self.myDelegate upDateUI];
    [self.myDelegate upDateText:str];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
